package com.kfm.kfmchat.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import lombok.Data;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@Slf4j
@Setter
public class ChatEventSourceListener extends EventSourceListener {

    private SseEmitter sseEmitter;

    // 监听到 eventSource 关闭
    @Override
    public void onClosed(@NotNull EventSource eventSource) {
        log.info("closed");
    }

    // 监听到有内容
    @Override
    public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {
        log.info("有内容{}", data);
        try {
            ChatCompletionResponse response = new JsonMapper().readValue(data, ChatCompletionResponse.class);
            sseEmitter.send(SseEmitter.event().data(response.getChoices().get(0).getDelta().getContent()));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    // 失败
    @Override
    public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {
        log.error("失败");
    }

    // 监听到 eventSource 打开
    @Override
    public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
        log.info("open");
    }
}
